package com.dmz.resold.apartment.service;

import com.dmz.resold.apartment.csp.CspQueryJob;
import com.dmz.resold.apartment.csp.HouseBean;
import com.dmz.resold.apartment.test.Xml2json;
import com.dmz.resold.apartment.tools.Base64Helper;
import com.dmz.resold.apartment.tools.RsaHelper;
import com.dmz.resold.apartment.webservice.PayServices;
import com.dmz.resold.apartment.webservice.PayServicesPortType;
import com.dmz.resold.apartment.webservice.String2StringMap;
import com.dmz.resold.apartment.webservice.String2StringMap.Entry;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Laptop
 */
@Slf4j
@Component
public class Handler {

    private String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLmjArr/oA9ZoLCb7/MBmDQPb5Le4CHLQTv4w4D2lbMCmcuBvA7SzpEg2GR46CzJFp/hdK7aQ0lK15iXxYLVNzLj+1ENwN/Ic9a3QwjjY3yssgQgv3C5ofcD7Go8+WNwCGPyfyM+WjG6gGqaK2y1ArFNCiW0vVCvMJ+6/l9hEg2wIDAQAB";

    private String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIuaMCuv+gD1mgsJvv8wGYNA9vkt7gIctBO/jDgPaVswKZy4G8DtLOkSDYZHjoLMkWn+F0rtpDSUrXmJfFgtU3MuP7UQ3A38hz1rdDCONjfKyyBCC/cLmh9wPsajz5Y3AIY/J/Iz5aMbqAaporbLUCsU0KJbS9UK8wn7r+X2ESDbAgMBAAECgYEAhyrYn0Q5PXqQF0Xtf6oz2akqOGQnQjZGiaR6gMEzUo6Ui+CbRraeOGE5ZR2dt7mYxla2eN8Vka+vM7FSCxJ/69YBlfFNwmECeADd+pEg2aort6wJCVZm8BwFtVCHnfvlPfCUGYOSHXJtMB+Kcg+RBmg/q+Jt4eJgptw0992q21ECQQD7U2at7yMuU4HYibvX7v3gmMWTDB+6ELEGyhdlisDEEeWFle8uVYXtVIFKpHLtwy4KbQthMivxdsSVgSk10mGTAkEAjjLa7HMjL7/WdiWdKwjplCFYlSsoDWATvGYaX+Q3i9fnKVJjwDGWxzzj21RqlDzzcycgV6EvdGKm5/LDJZnwmQJBAMUYzvmxBOIb00TCH3Jklu1AYhHD/E2rMWmlq1uSyUH61wlAYGbx4yoQj6S9+vPDkaPTiI0dD6E6B0lIFc2Dw8kCQDBB3/v4gwt0XjLQRwtQxfxIaMiO0dPgNDJusCq0x4kE52UlmcaizZml92n6twTBvpjowVgb0n/77squnz2GhZkCQD8XTJLuiBqT6DcIYI/uGZMtD4qWzQY5onl0mqNEfTWZV/6+K9hTUmL/NmLh4GNEAarWLPrYuS/8crw/3u8R/B0=";

    // 获取指令内容，返回新流水号
    public String getCommand(String bank, String lsh, String url) throws Exception {
        PayServices client = new PayServices(url);
        PayServicesPortType service = client.getPayServicesHttpPort();
        String2StringMap sm = service.getBankCommand(bank, lsh);
        if (!sm.getEntry().isEmpty()) {
            List<Entry> le = sm.getEntry();
            HashMap<String, String> map = new HashMap<String, String>();
            for (Entry entry : le) {
                map.put(entry.getKey(), entry.getValue());
                log.info("{}:{}", entry.getKey(), entry.getValue());
            }

            // 取得当前流水号
            String bclsh = map.get("LSH");
            byte[] jlsh = bclsh.getBytes(StandardCharsets.UTF_8);
            // 加密流水号
            byte[] re = RsaHelper.encryptData(jlsh, publicKey);
            byte[] btlsh = Base64Helper.encode(re).getBytes();
            // 加密后的流水号转为String类型
            String jmlsh = new String(btlsh, StandardCharsets.UTF_8);

            // 读取报文流
            byte[] input = service.readFile(bclsh, jmlsh);
            String file = new String(input, StandardCharsets.UTF_8);
            byte[] bt = RsaHelper.decryptData(Base64Helper.decode(file), privateKey);
            String fileContent = new String(bt, StandardCharsets.UTF_8);
            log.info("房管局指令:{}", fileContent);

            Entry enlsh = new Entry();
            enlsh.setKey("业务流水号");
            enlsh.setValue(map.get("LSH"));

            Entry en = new Entry();
            en.setKey("指令文件内容");
            en.setValue(fileContent);

            Entry command = new Entry();
            command.setKey("指令代码");
            command.setValue(map.get("COMMANDID"));

            log.info("------------------------[房管局->DMZ]-------------------------------------");
            log.info("{}:{}", enlsh.getKey(), enlsh.getValue());
            log.info("{}:{}", en.getKey(), en.getValue());
            log.info("{}:{}", command.getKey(), command.getValue());
            log.info("正常获取指令");
            System.out.println("正常获取指令");
            HouseBean hb = new HouseBean();

            log.info("------------------------[修改房管局报文]-------------------------------------");
            //房管局报文改成json
            String baowen = fileContent;
            log.info("处理前的报文:{}", baowen);
            List<Map<String, String>> list = Xml2json.readStringXml(baowen);
            JSONObject jsonObj = new JSONObject(list.get(0));
            fileContent = jsonObj.toString();
            log.info("处理后的报文:{}", fileContent);

            hb.setMessage(fileContent);
            hb.setCommandType(map.get("COMMANDID"));

            CspQueryJob cspa = new CspQueryJob();
            String result = cspa.cspQuery(hb);

            // 判断CSP返回结果为成功或失败
            // 判断CSP返回结果为成功或失败
            boolean resultFlag = false;
            if (result.substring(4, 8).equals("0000")) {
                resultFlag = true;
                //sendCommand("104", enlsh.getValue(), "", "", resultFlag,"成功", result.substring(8), "","0");
            }
            if (command.getValue().equals("20002")) {
                if (!result.substring(4, 8).equals("0030") && !result.substring(4, 8).equals("0058") && !result.substring(4, 8).equals("1111") && !result.substring(4, 8).equals("0048")) {
                    sendCommand("104", enlsh.getValue(), "", "", resultFlag, result, result.substring(8), "", "0");
                } else if (result.substring(4, 8).equals("0048")) {
                    resultFlag = true;
                    sendFalseCommand("104", enlsh.getValue(), "", "", resultFlag, result, result.substring(8), "", "0");
                } else {
                    String rev = cspa.updateLSHStatus("|" + enlsh.getValue() + "|" + "false" + "|");
                }
            } else if (command.getValue().equals("20001")) {
                if (!result.substring(4, 8).equals("0030") && !result.substring(4, 8).equals("0058") && !result.substring(4, 8).equals("0000") && !result.substring(4, 8).equals("0048")) {
                    resultFlag = false;
                    sendCommand("104", enlsh.getValue(), "", "", resultFlag, result, result.substring(8), "", "0");
                } else {
                    String rev = cspa.updateLSHStatus("|" + enlsh.getValue() + "|" + "false" + "|");
                }
            } else {
                sendCommand("104", enlsh.getValue(), "", "", resultFlag, result, result.substring(8), "", "0");
            }
            return enlsh.getValue();

        } else {
            log.error("------------------------[房管局指令为空！！退出程序!!!]  \r\n");
        }
        return "";
    }

    public boolean sendCommand(String bank, String lsh, String ftpid, String uid, boolean result, String message,
                               String rcommand, String url, String status) throws Exception {
        PayServices client = new PayServices(url);
        PayServicesPortType service = client.getPayServicesHttpPort();
        // 加密流水号
        byte[] res = RsaHelper.encryptData(lsh.getBytes(StandardCharsets.UTF_8), publicKey);
        byte[] btlsh = Base64Helper.encode(res).getBytes();
        String jmlsh = new String(btlsh, StandardCharsets.UTF_8);

        boolean r = false;
        log.info("------------------------[DMZ->房管局]---------------------------------------");
        log.info("流水号：{}", lsh);
        log.info("加密后流水号：" + jmlsh);
        if (result) {
            byte[] re = RsaHelper.encryptData(rcommand.getBytes(StandardCharsets.UTF_8), publicKey);
            byte[] fs = Base64Helper.encode(re).getBytes();
            String jmContent = new String(fs, StandardCharsets.UTF_8);
            log.info("文件字符串：" + rcommand);
            log.info("加密文件字符串：" + fs);
            int contentLen = jmContent.length();
            service.writeFile(lsh, jmlsh, jmContent, contentLen);
        }
        log.info("------------------------[房管局->DMZ]---------------------------------");
        log.info("bank:" + bank + "lsh:" + lsh + "result:" + result + "jmlsh:" + jmlsh + "status:" + status + "message:" + message);
        log.info("返回报文:" + rcommand);
        r = service.newReturnBankCommand(bank, lsh, result, message, jmlsh, status);
        log.info("反馈结果：" + r);

        CspQueryJob cspa = new CspQueryJob();
        String rev = cspa.updateLSHStatus("|" + lsh + "|" + r + "|");
        return r;
    }

    public boolean sendFalseCommand(String bank, String lsh, String ftpid, String uid, boolean result, String message,
                                    String rcommand, String url, String status) throws Exception {
        PayServices client = new PayServices(url);
        PayServicesPortType service = client.getPayServicesHttpPort();
        // 加密流水号
        byte[] res = RsaHelper.encryptData(lsh.getBytes(StandardCharsets.UTF_8), publicKey);
        byte[] btlsh = Base64Helper.encode(res).getBytes();
        String jmlsh = new String(btlsh, StandardCharsets.UTF_8);

        boolean r = false;
        log.info("------------------------[DMZ->房管局]---------------------------------------");
        log.info("流水号：" + lsh);
        log.info("加密后流水号：" + jmlsh);
        byte[] re = RsaHelper.encryptData(rcommand.getBytes(StandardCharsets.UTF_8), publicKey);
        byte[] fs = Base64Helper.encode(re).getBytes();
        String jmContent = new String(fs, StandardCharsets.UTF_8);
        log.info("文件字符串：" + rcommand);
        log.info("加密文件字符串：" + fs);
        int contentLen = jmContent.length();
        service.writeFile(lsh, jmlsh, jmContent, contentLen);
        log.info("------------------------[房管局->DMZ]---------------------------------");
        log.info("bank:" + bank + "lsh:" + lsh + "result:" + result + "jmlsh:" + jmlsh + "status:" + status + "message:" + message);
        log.info("返回报文:" + rcommand);
        r = service.newReturnBankCommand(bank, lsh, result, message, jmlsh, status);
        log.info("反馈结果：" + r);

        CspQueryJob cspa = new CspQueryJob();
        String rev = cspa.updateLSHStatus("|" + lsh + "|" + r + "|");
        return r;
    }

    public boolean sendCommand10101(String bank, String lsh, String ftpid, String uid, boolean result, String message,
                                    String rcommand, String url, String status) throws Exception {
        log.info("============10101=====================");
        PayServices client = new PayServices(url);
        PayServicesPortType service = client.getPayServicesHttpPort();
        // 加密流水号
        byte[] res = RsaHelper.encryptData(lsh.getBytes(StandardCharsets.UTF_8), publicKey);
        byte[] btlsh = Base64Helper.encode(res).getBytes();
        String jmlsh = new String(btlsh, StandardCharsets.UTF_8);

        boolean r = false;
        log.info("------------------------[DMZ->房管局]---------------------------------------");
        log.info("流水号：" + lsh);
        log.info("加密后流水号：" + jmlsh);

        log.info("------------------------[房管局->DMZ]---------------------------------");
        log.info("------" + bank + lsh + result + message + jmlsh + status);
        r = service.newReturnBankCommand(bank, lsh, result, message, jmlsh, status);

        log.info("反馈结果：" + r);

        CspQueryJob cspa = new CspQueryJob();
        String rev = cspa.updateLSHStatus("|" + lsh + "|" + r + "|");
        return r;
    }
}